using System.Xml.Linq;
using X = Adjunct.Framework.Nuspec.XNames.Package.Metadata.Dependencies.Dependency;

namespace Adjunct.Framework.Nuspec
{
	/// <summary>
	/// This class represents a dependency to another NuGet package.
	/// </summary>
	/// <remarks></remarks>
	public class NuspecDependency
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="NuspecDependency"/> class.
		/// </summary>
		/// <param name="id">The id.</param>
		/// <param name="version">The version.</param>
		/// <remarks></remarks>
		public NuspecDependency(string id = null, string version = null)
		{
			Id = id;
			Version = version;
		}

		/// <summary>
		/// The Id of the NuGet package dependency
		/// </summary>
		/// <value>The id.</value>
		/// <remarks></remarks>
		public string Id { get; set; }

		/// <summary>
		/// The version range specification for the NuGet package dependency.
		/// </summary>
		/// <value>The version.</value>
		/// <remarks></remarks>
		public string Version { get; set; }

		/// <summary>
		/// Clones this instance.
		/// </summary>
		/// <returns></returns>
		/// <remarks></remarks>
		public NuspecDependency Clone()
		{
			return new NuspecDependency(Id, Version);
		}

		/// <summary>
		/// Performs an explicit conversion from <see cref="Adjunct.Framework.Nuspec.NuspecDependency"/> to
		/// <see cref="System.Xml.Linq.XElement"/>.
		/// </summary>
		/// <param name="dependency">The dependency.</param>
		/// <returns>The result of the conversion.</returns>
		/// <remarks></remarks>
		public static explicit operator XElement(NuspecDependency dependency)
		{
			return (dependency == null)
			       	? null
			       	: new XElement(X.ElementName, dependency.Id.ToXAttribute(X.Id), dependency.Version.ToXAttributeIfNotEmpty(X.Version));
		}

		/// <summary>
		/// Performs an explicit conversion from <see cref="System.Xml.Linq.XElement"/> to
		/// <see cref="Adjunct.Framework.Nuspec.NuspecDependency"/>.
		/// </summary>
		/// <param name="element">The element.</param>
		/// <returns>The result of the conversion.</returns>
		/// <remarks></remarks>
		public static explicit operator NuspecDependency(XElement element)
		{
			if (element == null)
			{
				return null;
			}
			element.EnsureElementNameIs(X.ElementName);
			return new NuspecDependency(element.AttributeValue(X.Id), element.AttributeValue(X.Version, null));
		}
	}
}